package com.yanqu.road.server.channelserver.manager.activity.washe.game;

import com.yanqu.road.entity.activity.washe.eliminate.WasheBlock;
import com.yanqu.road.entity.activity.washe.eliminate.WasheGameData;
import com.yanqu.road.entity.enums.washe.eWasheBlockType;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

public class WasheFrameLogic {

    public static List<WasheBlock> randomFramePos(WasheGameData gameData, Random random, int num) {

        if (num <= 0) {
            return new ArrayList<>();
        }

        // 把非边缘的格子添加进去
        Set<WasheBlock> set = new HashSet<>();
        List<List<WasheBlock>> listList = gameData.getBlockList();
        for (int y = 1; y < listList.size() - 1; y++) {
            List<WasheBlock> list = listList.get(y);
            for (int x = 1; x < list.size() - 1; x++) {
                set.add(list.get(x));
            }
        }

        // 获取已有边框的格子，排除周边位置
        for (Map<Integer, WasheBlock> map : gameData.getFrameMap().values()) {
            for (WasheBlock frame : map.values()) {
                removeNearbyBlock(listList, set, frame.getX(), frame.getY());
            }
        }

        // 开始随机
        List<WasheBlock> resultList = new ArrayList<>();
        for (int i = 0; i < num && set.size() > 0; i++) {
            ArrayList<WasheBlock> list = new ArrayList<>(set);
            int index = random.nextInt(list.size());
            WasheBlock block = list.get(index);
            resultList.add(block);
            removeNearbyBlock(listList, set, block.getX(), block.getY());
        }

        return resultList;
    }

    /**
     * 移除自己及附近的格子
     *
     * @param listList 整个盘面
     * @param set      需要移除的set
     */
    public static void removeNearbyBlock(List<List<WasheBlock>> listList, Set<WasheBlock> set, int tmpX, int tmpY) {
        for (int y = tmpY - 1; y <= tmpY + 1; y++) {
            for (int x = tmpX - 1; x <= tmpX + 1; x++) {
                if (WasheGameLogic.isXyExist(listList, x, y)) {
                    set.remove(listList.get(y).get(x));
                }
            }
        }
    }

    public static boolean isCanBoomFrame(WasheBlock frame) {
        if (frame.getBlockType().getBigType() != eWasheBlockType.BIG_TYPE_FRAME) {
            return false;
        }

        if (frame.getBlockType() == eWasheBlockType.DuNHuangFeiTian) {
            return true;
        }
        return false;
    }

}
